package org.tity.test.config;

import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.URL;

import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.tity.commons.collection.MapUtil;
import org.tity.ends.transfer.Result;

import com.alibaba.fastjson.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BasicTester {

	 /**
     * @LocalServerPort 提供了 @Value("${local.server.port}") 的代替
     */
    @LocalServerPort
    protected int port;

    protected URL base;

    @Autowired
    protected TestRestTemplate restTemplate;
    
    @Before
    public void setUp() throws Exception {
        String url = String.format("http://localhost:%d/", port);
        System.out.println(String.format("port is : [%d]", port));
        this.base = new URL(url);
    }
 
    
    public void doTest(String url,String result,Object... ps) {
    	String fullurl=this.base.toString() + url;
    	System.out.println(fullurl);
        ResponseEntity<String> response = this.restTemplate.getForEntity(fullurl, String.class,ps);
        String rs=response.getBody();
        System.out.println(String.format(url+"\t测试结果为：%s", rs));
        assertTrue(result.equals(rs));
	}
    
    /**
     * 调用TityEnds端的服务
     * */
    public Result doEndsControllerTest(String url,Object... ps) {
    	String fullurl=this.base.toString() + url;
    	System.out.println(fullurl);
    	HttpHeaders headers = new HttpHeaders();
    	JSONObject jsonObj =(JSONObject)MapUtil.asLowerKeyMap(ps);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
 
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);

        String _result = restTemplate.postForObject(fullurl, formEntity, String.class);
        
        Result r=new Result();
        jsonObj=JSONObject.parseObject(_result);
        
        r.success(jsonObj.getBooleanValue("success"));
        
        System.out.println(url+",结果："+_result);

        return r;
    }
    
    
    private static String URL="http://127.0.0.1:8112/";
    
    public static Result doFastEndsTest(String url,Object... ps) {
    	 String fullurl=URL+url;
    	 OkHttpClient client = new OkHttpClient();    
    	 JSONObject jsonObj =(JSONObject)MapUtil.asLowerKeyJSONObject(ps);
         //3, 发起新的请求,获取返回信息    
//         RequestBody body = new FormBody.Builder()    
//                             .add("useName", "abc")//添加键值对    
//                             .add("usePwd", "321")    
//                             .build();    
         okhttp3.FormBody.Builder builder=new FormBody.Builder();
         
         for (Object key : jsonObj.keySet()) {
        	 builder.add(key+"", jsonObj.getString(key+""));
		 }
         
         RequestBody body=builder.build();
         
         Request request = new Request.Builder()    
                             .url(fullurl)    
                             .post(body)    
                             .build();
         //
         Result r=new Result();
         try {
			 Response response = client.newCall(request).execute();
			 if(response.isSuccessful())
			 {
			     String str = response.body().string();
			     System.out.println(url+",结果："+str);

			     jsonObj=JSONObject.parseObject(str);
			     r.success(jsonObj.getBooleanValue("success"));
			     return r;
			 }
			 else
			 {
				 return r;
			 }
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
         
    }
	
}
